<?php

namespace App\Traits;

trait UploaderTrait
{
    protected $instance = null;
    protected $disk = 'public';
    protected $dirname = 'uploads';
    protected $filename = 'file';
    protected $imageExt = ['jpg', 'png', 'jpeg'];

    public function uploader()
    {
        $this->instance = request()->file($this->filename);
        return is_array($this->instance) ? $this->batch() : $this->save($this->instance);
    }

    public function save($file): string
    {
        $name = $this->getSaveName(request()->input('original', ''), $this->getExtension($file));
        return asset('storage/' . $file->storeAs($this->dirname . DIRECTORY_SEPARATOR . date('Ym'), $name, $this->disk));
    }

    public function batch(): array
    {
        $res = [];
        foreach ($this->instance as $file) {
            $res[] = $this->save($file);
        }
        return $res;
    }

    protected function getSaveName(string $filename = '', string $extension = ''): string
    {
        if ($filename) {
            return $filename;
        }
        return sprintf('%s%s.%s', time(), substr(microtime(), 2, 4), $extension);
    }

    protected function getExtension($file): string
    {
        return in_array($file->extension(), $this->imageExt) ? 'jpg' : $file->getClientOriginalExtension();
    }
}
